<?php
namespace PsiFramework\Applications\AlloMediaPortal\Classes\Services;

import("Classes.Services.AbstractService");

use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Services\AbstractService;
use \PsiFramework\Classes\Util\HTTP\Request;
use \PsiFramework\Classes\Util\Object\EMail;
use \PsiFramework\Classes\Util\Manager\ApplicationManager;
use \PsiFramework\Classes\Util\Manager\ParametersManager;

/**
 * Bibliotheque
 * Gestion de ma bibliothèque
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Service de listing des auteurs
 *
 * @package Services
 */
class SendNewPasswordService extends AbstractService
{

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * The main function of the method which is called every time
     * an service is created by the front controller.
     *
     * @param $request      the HTTP request to be treated by the action
     */
    public function execute(Request $request)
    {
        parent::execute($request);

        $userDao = DAOFactory::getDAO('User');

        $userId = $request->getParameter('user_id');
        $user = $userDao->retrieveByPk($userId);

        $ok = false ;

        if (!is_null($user)) {
            $decryptedPwd = uniqid();
            $pwd = md5($decryptedPwd);

            $user->setPassword($pwd);
            $ok = $userDao->save($user);
        }

        if ($ok) {
            $paramManager = ParametersManager::getInstance();
            $applicationsParameters
                = $paramManager->getApplicationsParameters();

            $contact = $applicationsParameters->getContact();
            $subject = "Inscription" ;
            $message = $decryptedPwd ;

            $application = ApplicationManager::getInstance()->getApplication();
            $appConfigDao = DAOFactory::getDAO('ApplicationConfiguration');
            $appConfig = $appConfigDao->retrieveByName($application->getName());

            if (!is_null($appConfig)) {
                $contact = $appConfig->getParameters()->get('email');
                $page
                    = $appConfig->getParameters()
                        ->get('new_password_message')
                        ->getObject();
                if (!is_null($page)) {
                    $subject = $page->getTitle();
                    $message
                        = str_replace(
                            '<password>',
                            $decryptedPwd,
                            $page->getContent()
                        );
                }
            }

            $email = new EMail($contact, $user->getEmail(), $subject, $message);
            //send email to the user
            $email->send();

            echo 'ok' ;
        }
    }
}
